package com.shangjinrong.controller.api;

import com.shangjinrong.excption.BusinessException;
import com.shangjinrong.result.R;
import com.shangjinrong.result.ResponseEnum;
import com.shangjinrong.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Naruto
 */


@RestController
@CrossOrigin
@RequestMapping("api/file")
public class FileController {

    @Autowired
    private FileService fileService;


    @PostMapping("upload")
    public R upload(@RequestParam("file") MultipartFile file,
                    @RequestParam("module") String module) {

        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            String uploadUrl = fileService.upload(inputStream, module, originalFilename);

            return R.ok().message("文件上传成功").data("url", uploadUrl);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }

    }

    @DeleteMapping("remove")
    public R remove(@RequestParam("url") String url) {
        fileService.removeFile(url);

        return R.ok().message("文件删除成功");
    }
}
